<template>
  <div class="center">
    <n-card style="min-width: 300px; flex: 1">
      <n-space>
        <n-h3 style="margin: 0">角色表单</n-h3>
      </n-space>
      <n-space style="margin: 20px 0">
        <n-button size="small" round @click="addrolegroup">新增角色组</n-button>
        <!-- <n-button size="small" round @click="addrole">新增角色</n-button> -->
      </n-space>
      <n-tree
        block-line
        :data="data.value"
        @update:selected-keys="selected"
        :default-expanded-keys="defaultExpandedKeys"
        :selectable="true"
        :cancelable="false"
      />
    </n-card>
    <n-card style="width: 0; flex: 4">
      <n-space>
        <n-h3>{{ name }}</n-h3>
        <n-icon style="position: relative; top: 3px" size="20">
          <UsergroupAddOutlined />
        </n-icon>
        <n-h3>{{ total }}</n-h3>
      </n-space>
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        :pagination="pagination"
        :scroll-x="800"
      >
        <template #tableTitle>
          <n-space vertical>
            <n-space>
              <n-h5>分配菜单:</n-h5>
              <n-gradient-text type="success" v-if="menu.length < 1">-</n-gradient-text>
              <n-gradient-text type="success" v-else v-for="(item,index) in menu" :key="index">{{ item.menuName}}</n-gradient-text>
              <n-h5>分配额外权限:</n-h5>
              <n-button text type="primary" size="small" @click="toView('查看权限')"> 查看权限 </n-button>
            </n-space>
            <n-space>
              <n-button size="small" @click="addTable"> 添加用户 </n-button>
              <n-button size="small"> 移除用户 </n-button>
            </n-space>
          </n-space>
        </template>
        <template #toolbar>
          <n-space>
            <n-input
              size="small"
              v-model:value="formValue.keyword"
              clearable
              placeholder="请输入搜索内容"
            >
              <template #prefix>
                <n-icon>
                  <Search />
                </n-icon>
              </template>
            </n-input>
            <n-button size="small" type="primary" @click="reloadTable">查询</n-button>
          </n-space>
        </template>
      </BasicTable>
    </n-card>
    <Model
      :showModal="showModal"
      :FormData="FormData"
      :formValue="formValue"
      :title="title"
      :rules="rules"
      @ModelClick="ModelClick"
      @close="close"
    >
    </Model>
    <ModelBox
      :ModelBox="ModelBox"
      :center="center"
      :title="title"
      @determine="determine"
    ></ModelBox>
    <n-modal style="width:50%" v-model:show="Modal" :show-icon="false" preset="dialog" title="Dialog">
      <template #header>
        <div>{{modelTitle}}</div>
      </template>
      <div>
        <BasicTable
          :columns="Modelcolumns"
          :request="Table"
          :row-key="(row) => row.id"
          :pagination="false"
          ref="actionRef"
        >
        </BasicTable>
      </div>
      <template #action style="justify-content: center;">
        <n-button type="primary" size="small" @click="closeModel"> 关闭 </n-button>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts">
import { h, defineComponent, reactive, ref,onActivated } from 'vue';
import { useMessage, NButton, NDropdown, NIcon } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, useForm } from '@/components/Form/index';
import { fetchRoleTree, addRoleGroup,addRole, deleteRoleGroup, deleteRole,fetchUserListPageByRoleId,deleteUserRole,updateRoleGroup,fetchAuthListByRoleId,fetchMenuListByRoleId,} from '@/api/Role/index'; //导入接口文件
import { useRouter } from 'vue-router';
import { Model } from '@/components/Model';
import { ModelBox } from '@/components/ModelBox';
import Search from '@/assets/icons/Search.vue';
import { UsergroupAddOutlined } from '@vicons/antd';
export default defineComponent({
  name:'roleManagement',
  components: {
    BasicTable,
    BasicForm,
    UsergroupAddOutlined,
    Model,
    ModelBox,
    Search,
  },
  setup() {
    const columns = [
      {
        type: 'selection',
        fixed: 'left',
      },
      {
        width: 100,
        title: '序号',
        key: 'Serial',
      },
      {
        title: '账号',
        key: 'userName',
        render(row) {
          if (row.userName) {
            return row.userName;
          } else {
            return '-';
          }
        },
      },
      {
        title: '姓名',
        key: 'name',
        render(row) {
          if (row.name) {
            return row.name;
          } else {
            return '-';
          }
        },
      },
    ];
    const Modelcolumns = [
      {
        title: '权限名称',
        key: 'authName',
      },
      {
        title: '接口地址',
        key: 'uri',
        render(row) {
          if (row.uri) {
            return row.uri;
          } else {
            return '-';
          }
        },
      },
      {
        title: '备注',
        key: 'remark',
        render(row) {
          if (row.remark) {
            return row.remark;
          } else {
            return '-';
          }
        },
      },
    ];
    const actionRef = ref();
    const router = useRouter();
    const formRef: any = ref(null);
    const center = ref(null);
    const message = useMessage();
    const title = ref(null);
    const showModal = ref(false);
    const ModelBox = ref(false);
    const formBtnLoading = ref(false);
    const formValue = ref({ keyword: '' });
    const FormData = ref([]);
    const Modal = ref(false)
    const modelTitle = ref(null);
    const formParams = ref({
      name: '',
      address: '',
      date: null,
    });
    const params = ref({ size: 10, page: 1 });
    const Obj = ref({});
    const menu = ref([]);
    const actionColumn = reactive({
      title: '操作',
      key: 'action',
      fixed: 'right',
      render(record) {
        return h(TableAction as any, {
          text: true,
          actions: [
            {
              label: '删除',
              type: 'primary',
              text: true,
              onClick: handleDelete.bind(null, record),
            },
          ],
          select: (key) => {
            message.info(`您点击了，${key} 按钮`);
          },
        });
      },
    });
    const [register, {}] = useForm({
      gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
      labelWidth: 80,
    });
    const total = ref(0);
    const name = ref('');
    //表格数据
    const TableData = ref(null);
    const loadDataTable = async () => {
      if (params.value.roleId) {
        TableData.value = await fetchUserListPageByRoleId({ ...params.value });
        TableData.value.list.map((res, index) => {
          res.Serial = ++index;
        });
      }
      //总条数
      total.value = TableData.value ? TableData.value.total : '0';
      
      return TableData.value;
    };

    //查询
    const reloadTable = () => {
      params.value = { ...params.value, ...formValue.value };
      actionRef.value.reload();
    };
    //删除
    const handleDelete = (record: Recordable) => {
      Obj.value = record;
      ModelBox.value = true;
      title.value = '删除';
      center.value = '是否确定要删除?';
    };
    //删除确定按钮
    const determine = async (e) => {
      ModelBox.value = e;
      if (title.value == '删除') {
        await deleteUserRole({ userId: Obj.value.id, roleId: roleId.value.roleId });
        actionRef.value.reload();
      }
    };
    //新增角色组
    const addrolegroup = async () => {
      FormData.value = [
        {
          label: '分组名称',
          type: 'n-input',
          enName: 'roleGroupName',
          clearable: true,
          size: 'small',
          show: true,
          placeholder: '请输入分组名称',
          span: 24,
        },
      ];
      formValue.value = {};
      title.value = '新增角色组';
      showModal.value = true;
    };
    //新增
    const addTable = async () => {
      // formValue.value = {};
      // title.value = '添加用户';
      // showModal.value = true;
    };
    //模态框确定
    const ModelClick = async (e) => {
      if (title.value == '新增角色组') {
        await addRoleGroup(formValue.value);
        Role();
      } else if (title.value == '编辑角色组') {
        const Obj = ref({});
        Obj.value.roleGroupName = formValue.value.roleGroupName;
        Obj.value.id = roleId.value.roleId;
        await updateRoleGroup(Obj.value);
        Role();
        // console.log(roleId.value)
      }
      showModal.value = e;
      ModelBox.value = e;
    };
    //模态框关闭
    const close = (e) => {
      showModal.value = e;
      ModelBox.value = e;
    };
    const closeModel = () => {
      Modal.value = false
    }
    onActivated(() => {
      //执行获取所有角色树状方法
      Role();
      actionRef.value.reload();
    })

    //存放树状数据
    const data = ref([]);
    const options = ref([]);
    //查询所有角色(树状)
    const Role = async () => {
      data.value = [];
      const res = await fetchRoleTree();
      //处理角色数据格式
      options.value = res.map((r, i) => {
        return {
          label: r.roleGroupName,
          key: r.roleGroupId,
          children: r.roleList,
          suffix: () =>
            h(
              NDropdown,
              {
                trigger: 'click',
                options: [
                  { label: '添加角色', key: 'add' },
                  { label: '编辑', key: 'edit' },
                  { label: '删除', key: 'del' },
                ],
                onSelect: (e) => handleSelect(r.roleGroupId, deleteRoleGroup, e, r.roleGroupName),
              },
              {
                default: () =>
                  h(NButton, { text: true, type: 'primary' }, { default: () => '操作' }),
              }
            ),
        };
      });
      options.value.map((r) => {
        r.children = r.children.map((res, i) => {
          return {
            label: res.roleName,
            key: res.id,
            suffix: () =>
              h(
                NDropdown,
                {
                  trigger: 'click',
                  options: [
                    { label: '角色配置', key: 'role' },
                    { label: '删除', key: 'del' },
                  ],
                  onSelect: (e) => handleSelect(res.id, deleteRole, e),
                },
                {
                  default: () =>
                    h(NButton, { text: true, type: 'primary' }, { default: () => '操作' }),
                }
              ),
            prefix: () => h(NIcon, { type: 'primary' }, { default: [h(UsergroupAddOutlined)] }),
          };
        });
        //如果children为空就删除该字段
        if (r.children.length == 0) {
          delete r.children;
        }
      });
      data.value = options;
    };

    //悬浮事件
    const handleSelect = async (v, url, e, name) => {
      //删除
      if (e == 'del') {
        await url(v);
        Role();
      } else if (e == 'add') {
        router.push({ name: 'addRole', params: { roleGroupId: v } });
      } else if (e == 'edit') {
        FormData.value = [
          {
            label: '分组名称',
            type: 'n-input',
            enName: 'roleGroupName',
            clearable: true,
            size: 'small',
            show: true,
            placeholder: '请输入分组名称',
            span: 24,
          },
        ];
        formValue.value.roleGroupName = name;
        title.value = '编辑角色组';
        showModal.value = true;
      }
    };

    //把选中的角色组下的id保存
    const roleId = ref({});
    //树形选中事件
    const selected = async (key) => {
      roleId.value.roleId = key[0];
      params.value = { ...params.value, ...roleId.value };
      data.value.value.map((res) => {
        if (res.key == key[0]) {
          name.value = res.label;
          console.log(res.label);
        }
        if (res.hasOwnProperty('children')) {
          res.children.map((r) => {
            if (r.key == key[0]) {
              name.value = r.label;
            }
          });
        }
      });
      const menuData = await fetchMenuListByRoleId(roleId.value.roleId);
      menu.value = menuData;
      actionRef.value.reload();
    };

    //查看菜单和权限
    const jurisdictionTable = ref({ list:[] })
    const toView = async (row) => {
      modelTitle.value = row
      Modal.value = true
      await Table();
    }

    const Table = async () => {
      if(roleId.value.roleId){
        const data = await fetchAuthListByRoleId(roleId.value.roleId);
        jurisdictionTable.value.list = data
      }
      return jurisdictionTable.value
    }
    return {
      Table,
      data,
      menu,
      options,
      defaultExpandedKeys: ref(['1434781876265943040']),
      rules: {
        roleGroupName: [
          {
            required: true,
            validator(rule, value) {
              if (!value) {
                return new Error('请输入分组名称');
              } else if (!/^[\u4e00-\u9fa5]+$/.test(value)) {
                return new Error('角色组应该为中文');
              }
              return true;
            },
            trigger: ['input', 'blur'],
          },
        ],
      },
      jurisdictionTable,
      closeModel,
      Modelcolumns,
      total,
      modelTitle,
      TableData,
      name,
      handleSelect,
      router,
      formRef,
      roleId,
      Obj,
      message,
      actionRef,
      showModal,
      ModelBox,
      Modal,
      toView,
      formBtnLoading,
      formParams,
      params,
      actionColumn,
      register,
      loadDataTable,
      reloadTable,
      handleDelete,
      selected,
      columns,
      determine,
      ModelClick,
      close,
      addTable,
      addrolegroup,
      title,
      FormData,
      formValue,
      center,
    };
  },
});
</script>

<style lang="less" scoped>
.center {
  display: flex;
  margin: 20px;
}
</style>
